<!-- 商品销售规格编辑弹窗 -->
<template>
  <div class="ele-body">
    <a-card :title="specificationStockModalApp.title" :bordered="false">
      <a-form
        ref="form2"
        :model="specificationStockModalApp.specificationStock"
        :rules="specificationStockModalApp.rules"
        :label-col="{md: {span: 7}, sm: {span: 24}}"
        :wrapper-col="{md: {span: 17}, sm: {span: 24}}">
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="商品:" name="commodityId">
              <m-entity-select
                :disabled="specificationStockModalApp.id"
                :default-value="specificationStockModalApp.specificationStock.commodityName"
                v-model:value="specificationStockModalApp.specificationStock.commodityId"
                placeholder="请选择商品"
                @onChange="changeCommodity"
                show-options-name="description"
                module="good"
                entity="Commodity"
                class="ele-fluid"
              />
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="规格:" name="specification">
              <a-input
                v-model:value="specificationStockModalApp.specificationStock.tempSpecification"
                disabled="true"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24" v-for="(item,key) in specifications" :key="key">
            <a-form-item :label="item.description+':'" name="stock" >
              <a-radio-group  v-model:value="specificationStockModalApp.specificationStock.tempSpecification[key]" size="small" v-for="(subItem,subKey) in item.children" :key="subKey">
                <a-radio-button :value="subItem.description">{{subItem.description}}</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="原价格:" name="oldPrice">
              <a-input
                v-model:value="specificationStockModalApp.specificationStock.oldPrice"
                placeholder="请输入原价格"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="销售价格:" name="price">
              <a-input
                v-model:value="specificationStockModalApp.specificationStock.price"
                placeholder="请输入销售价格"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="库存:" name="stock">
              <a-input
                v-model:value="specificationStockModalApp.specificationStock.stock"
                placeholder="请输入库存"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="图片:" name="img">
              <image-upload :associate-form-id="specificationStockModalApp.specificationStock.eid" associate-form-name="specificationStock" ref="imageRef" ></image-upload>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
              <!--class="ele-pull-right"-->
              <div v-if="specificationStockModalApp.display">
                <teleport to="#specificationStockEditModalFooter">
                  <div>
                    <a-space size="middle">
                      <a-button @click="specificationStockListApp.editModalShowing=false">取消
                      </a-button>
                      <a-button
                        type="primary"
                        @click="onSubmit(specificationStockModalApp.specificationStock)"
                        :loading="loading">提交
                      </a-button>
                      <!--<a-button v-if="!eid"
                                type="dashed"
                                @click="continueSubmit"
                                :loading="loading">继续提交
                      </a-button>-->
                    </a-space>
                  </div>
                </teleport>
              </div>
              <div v-if="!specificationStockModalApp.display">
                <a-space size="middle">
                  <a-button @click="onBack()">返回列表</a-button>
                  <a-button
                    type="primary"
                    @click="onSubmit(specificationStockModalApp.specificationStock)"
                    :loading="loading">提交
                  </a-button>
                  <!--<a-button v-if="!eid"
                            type="dashed"
                            @click="continueSubmit"
                            :loading="loading">继续提交
                  </a-button>-->
                </a-space>
              </div>

            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

  </div>

</template>

<script>
import {defineComponent, inject, reactive, onMounted, ref} from 'vue'
import {useRoute, useRouter} from "vue-router"
import {SpecificationStockService} from "@/views/mall/good/specificationStock/specificationStockService";
import {VXETable} from 'vxe-table'
import {useStore} from "vuex";
import regions from 'ele-admin-pro/packages/regions.js';
import {SpecificationService} from "@/views/mall/good/specification/specificationService";
import ImageUpload from "@/components/MImageUpload/ImageUpload";

import MEntitySelect from "@/components/MEntity/entitySelect";
import attachmentService from "@/components/MFileUpload/attachmentService";

export default defineComponent({
  components: {
    MEntitySelect,
    ImageUpload
  },
  setup() {
    // 省市区数据
    const cityData = regions
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    let routeId = route.params.id;
    let specificationStockListApp = inject('specificationStockListApp', reactive({}));
    let specificationStockGrid = inject('specificationStockGrid', reactive({}))
    const specificationStockModalApp = reactive({
      id: null,
      specificationStock: {
        specification:[],
      },
      isEdit: false,
      display: false
    });
    specificationStockModalApp.rules = {
      commodityId: [
        {
          required: false,
          type: 'number',
          message: '请输入商品',
          trigger: 'blur'
        }
      ],
      commodityName: [
        {
          required: false,
          type: 'string',
          message: '请输入商品',
          trigger: 'blur'
        }
      ],
      specification: [
        {
          required: false,
          type: 'string',
          message: '请输入规格',
          trigger: 'blur'
        }
      ],
      stock: [
        {
          required: false,
          type: 'string',
          message: '请输入描述',
          trigger: 'blur'
        }
      ],
    }

    onMounted(() => {
      //清理数据
      specificationStockModalApp.specificationStock = reactive({});
      if (routeId) {//路由
        specificationStockModalApp.id = routeId;
        specificationStockModalApp.display = false;
        findSpecificationStock(specificationStockModalApp.id);
      } else if (specificationStockListApp.editModalForEdit) {//修改弹窗
        specificationStockModalApp.id = specificationStockListApp.currentId;
        specificationStockModalApp.display = true;
      } else if (!specificationStockListApp.editModalForEdit && specificationStockListApp.addModalForEdit) {//新增弹窗
        specificationStockModalApp.display = true;
      } else {
        specificationStockModalApp.title = "新增学生";
      }
      if (specificationStockModalApp.id) findSpecificationStock(specificationStockModalApp.id);
    })

    const findSpecificationStock = (id) => {
      SpecificationStockService.findSpecificationStockForView(id).then((res) => {
        specificationStockModalApp.specificationStock = res.data;
        specificationStockModalApp.specificationStock.tempSpecification=res.data.specification;
        //TODO:为编辑准备.
        // specificationStockModalApp.title = "编辑学生 " + specificationStockModalApp.specificationStock.name;
        console.log(res.data)
      }).catch(error => {
        VXETable.modal.message({content: `查找出错，原因是：${error.message}`, status: 'error'});
      })
    }

    /*TODO:提交 新增&编辑*/
    const onSubmit = (data) => {
      // debugger;
      //当为数组时用逗号连接

      if (data.eid) {
        //修改
        SpecificationStockService.updateSpecificationStock(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          saveFile(res.data.eid,"specificationStock")
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      } else {
        let isTrue = true;
        data.tempSpecification.forEach(e=>{
          if(e==''||e==undefined){
            isTrue=false;
            return;
          }
        })
        if(!isTrue){
          VXETable.modal.message({content: '请选择完全规格属性', status: 'warning'});
          return;
        }

        data.specification=data.tempSpecification.join(",")
        //新增
        SpecificationStockService.saveSpecificationStock(data).then((res) => {
          console.log(res)
          saveFile(res.data.eid,"specificationStock")
          VXETable.modal.message({content: '操作成功', status: 'success'});
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      }
    }

    /*TODO:继续提交*/
    const continueSubmit = () => {
      VXETable.modal.message({content: 'error 提示', status: 'error'});
    }

    /*TODO:返回列表*/
    const onBack = () => {
      router.push(`/mall/good/specificationStock`);
      store.dispatch('user/tabRemove', route.fullPath);
      setTimeout(() => {
        specificationStockGrid.value.commitProxy("query");
      }, 1500);
      specificationStockListApp.editModalShowing = false;
    }
    const specifications=ref([]);
    const changeCommodity = (commodity) => {
      console.log(commodity)
      SpecificationService.findSpecificationByCommodityId(commodity.eid).then((res)=>{
        specificationStockModalApp.specificationStock.tempSpecification=[];
        res.data.forEach(()=>{
          specificationStockModalApp.specificationStock.tempSpecification.push("");
        })
        specifications.value=res.data;

      })
    }
    const imageRef=ref(null)
    // const fileList=ref([])
    // const changeFiles = (files) => {
    //   fileList.value =files;
    //   console.log("files1",files)
    //   console.log("files2",fileList.value);
    //   console.log(imageRef.value.fileList)
    // }

    let saveFile = (associateFormId,associateFormName) => {
      // console.log(fileList.value)
      // debugger
      if (imageRef.value.fileList.length !== 0) {
        let formData = new FormData();
        //表单名--对应实体表名
        let formDto = {associateFormId: associateFormId, associateFormName: associateFormName};
        let fileUploadDto = JSON.stringify(formDto)
        formData.append("fileUploadDto", new Blob([fileUploadDto], {type: "application/json"}));
        imageRef.value.fileList.forEach(file => {
          formData.append('files', file)
        });

        attachmentService.saveFile(formData).then(() => {
          imageRef.value.fileList = [];
          VXETable.modal.message({content: '上传成功', status: 'success'});
          //更改上传组件的状态为编辑状态
          // operatorType = "edit";
          // cleanFileList(associateFormId,associateFormName);
        }).catch((error) => {
          // loading.value = false
          VXETable.modal.message({content: '上传失败' + `系统错误，原因是：${error.message}`, status: 'error'});
        });
      }

    }
    // const changeSpecification = (value,index) => {
    //   console.log(value,index,specificationStockModalApp.specificationStock.test)
    //   specificationArray.value[index]=value;
    //
    //   // console.log(specificationStockModalApp.specificationStock.specification)
    //   // specificationStockModalApp.specificationStock.specification[index]=value;
    // }
    return {
      cityData,
      routeId,
      specificationStockListApp,
      specificationStockModalApp,
      onSubmit,
      continueSubmit,
      onBack,
      changeCommodity,
      specifications,
      // changeFiles,
      saveFile,
      imageRef
      // changeSpecification
    }

  },
})
</script>

<style scoped>

</style>
